package com.ruoyi.xqsp.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.quyang.voice.utils.HttpClient;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.status.ResponseUtil;
import com.ruoyi.xqsp.domain.*;
import com.ruoyi.xqsp.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Api(value = "用户管理", tags = "用户管理")
@RestController
@RequestMapping("/xqsp/vip")
public class VipController {


    @Autowired
    VipCategoryService vipCategoryService;


    @Autowired
    UserVipService userVipService;

    @Autowired
    ISpUsersService spUsersService;

    @Autowired
    MsgsCollectArchivedService msgsCollectArchivedService;

    @Autowired
    PaymentChannelService paymentChannelService;

    @Autowired
    ISpUsersService usersService;

    @Autowired
    VideoDiscountService videoDiscountService;

    @Autowired
    GoldListService goldListService;

    @Autowired
    ReceiptCodeService receiptCodeService;


    @Autowired
    RedisCache redisCache;

    @Value("${epay.pid}")
    String pid;

    @Value("${epay.key}")
    String key;


    @ApiOperation("vip 分类")
    @ApiImplicitParam(dataType = "Integer" ,name = "id",value = "会员id  0：查询所有 ，对于id查询单个的")
    @GetMapping("/list")
    public ResponseUtil List(Integer id){
        if (id == null){
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.orderByAsc("type");
             return ResponseUtil.success(vipCategoryService.list(wrapper));
        }else {
            return ResponseUtil.success(vipCategoryService.getById(id));
        }
    }


    @PostMapping("/openVIp")
    @ApiOperation(value = "开通会员", notes = "开通会员")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id" ,name = "userId",dataType = "Integer"),
            @ApiImplicitParam(value = "vip字段id" ,name = "vId",dataType = "Integer"),
    })
    public ResponseUtil openVIp(Integer userId,Integer vId){


        return userVipService.openVIp(userId,vId);

    }




    @PostMapping("/isMember")
    @ApiOperation(value = "是否是会员", notes = "是否是会员")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id" ,name = "userId",dataType = "Integer"),
            @ApiImplicitParam(value = "vip字段id" ,name = "vId",dataType = "Integer"),
    })
    public ResponseUtil isMember(Integer userId,Integer vId){



        HashMap map = new HashMap();
        map.put("isMember",false);
        SpUsers users = usersService.getById(userId);
        Date date = new Date();
        if (users !=null && users.getUserMembersDay().compareTo(date) > -1){
            VideoDiscount byId = videoDiscountService.getById(2);
            Double discount = byId.getDiscount();
            map.put("isMember",true);
            map.put("discount",discount);
        }else {
            VideoDiscount byId = videoDiscountService.getById(1);
            Double discount = byId.getDiscount();
            map.put("isMember",false);
            map.put("discount",discount);
        }


        return ResponseUtil.success(map);

    }

    /**
     * 会员记录
     * @Author lipeng
     * @Date 2022/5/23 22:00
     * @param userId
     * @return com.ruoyi.common.utils.status.ResponseUtil
     */
    @PostMapping("/membershipRecords")
    public ResponseUtil membershipRecords(Integer userId,Integer type,Integer pageNum, Integer pageSize){


        return userVipService.membershipRecords(userId,type,pageNum,pageSize);

    }


    /**
     * 消息记录
     * @Author lipeng
     * @Date 2022/5/23 22:00
     * @param userId
     * @return com.ruoyi.common.utils.status.ResponseUtil
     */
//    @Log(title = "",BusinessType.OTHER)
    @Log(title = "消息记录", businessType = BusinessType.OTHER)
    @PostMapping("/messageLog")
    public ResponseUtil messageLog(Integer userId,Integer toUserId,Integer pageNum, Integer pageSize){

        PageHelper.startPage(pageNum,pageSize);
        QueryWrapper<MsgsCollectArchived> wrapper = new QueryWrapper();

        wrapper.and(w ->w.eq("src_uid",userId).eq("dest_uid",toUserId));
        wrapper.or(w ->w.eq("src_uid",toUserId).eq("dest_uid",userId));
        wrapper.orderByDesc("msg_time");
        List<MsgsCollectArchived> list = msgsCollectArchivedService.list(wrapper);
        Collections.reverse(list);

        return ResponseUtil.success(PageInfo.of(list));

    }

    /**
     * 消息记录
     * @Author lipeng
     * @Date 2022/5/23 22:00
     * @param userid
     * @return com.ruoyi.common.utils.status.ResponseUtil
     */
//    @Log(title = "",BusinessType.OTHER)
    @Log(title = "消息记录", businessType = BusinessType.OTHER)
    @PostMapping("/messageLogV2")
    public ResponseEntity messageLogV2(Integer userid){
//        {
//            "29": {
//            "spread0": "true",
//                    "history": {
//                "friend44": {
//                    "sign": "",
//                            "id": "44",
//                            "avatar": "https://video.imomo1.com/group1/M00/00/6C/ia8B-mLydyiEYKzCAAAAAD0M-Bc340.png",
//                            "username": "44",
//                            "status": "online",
//                            "name": "44",
//                            "type": "friend",
//                            "historyTime": 1660993636022
//                }
//            },
//            "chatlog": {
//                "friend44": [{
//                    "username": "客服1111",
//                            "avatar": "https://video.imomo1.com/group1/M00/00/6C/ia8B-mLydyiEYKzCAAAAAD0M-Bc340.png",
//                            "id": "44",
//                            "type": "friend",
//                            "content": "1",
//                            "timestamp": 1660993638422,
//                            "mine": true
//                }, {
//                    "username": "44",
//                            "avatar": "https://video.imomo1.com/group1/M00/00/6C/ia8B-mLydyiEYKzCAAAAAD0M-Bc340.png",
//                            "id": "44",
//                            "type": "friend",
//                            "content": "2",
//                            "timestamp": 1660993656850
//                }]
//            }
//        }
//        }

//        {"29":{"spread0":"true",
//                "history":{
//            "friend44":{"sign":"","id":"44","avatar":"https://video.imomo1.com/group1/M00/00/6C/ia8B-mLydyiEYKzCAAAAAD0M-Bc340.png","username":"44","status":"online","type":"friend","name":"44","historyTime":1660997160159},
//            "friend30":{"sign":"","id":"30","avatar":"https://video.imomo1.com/group1/M00/00/6C/ia8B-mLydyiEYKzCAAAAAD0M-Bc340.png","username":"30","status":"online","name":"30","type":"friend","historyTime":1660994820133},
//            "friend31":{"sign":"","id":"31","avatar":"https://video.imomo1.com/group1/M00/00/6C/ia8B-mLydyiEYKzCAAAAAD0M-Bc340.png","username":"31","status":"online","name":"31","type":"friend","historyTime":1660994823557},
//            "friend32":{"sign":"","id":"32","avatar":"https://video.imomo1.com/group1/M00/00/6C/ia8B-mLydyiEYKzCAAAAAD0M-Bc340.png","username":"32","status":"online","name":"32","type":"friend","historyTime":1660994830413}},
//            "chatlog":{
//            "friend44":[
//                {"username":"客服1111","avatar":"https://video.imomo1.com/group1/M00/00/6C/ia8B-mLydyiEYKzCAAAAAD0M-Bc340.png","id":"44","type":"friend","content":"1","timestamp":1660993638422,"mine":true},
//                {"username":"44","avatar":"https://video.imomo1.com/group1/M00/00/6C/ia8B-mLydyiEYKzCAAAAAD0M-Bc340.png","id":"44","type":"friend","content":"2","timestamp":1660993656850},
//                {"username":"44","avatar":"https://video.imomo1.com/group1/M00/00/6C/ia8B-mLydyiEYKzCAAAAAD0M-Bc340.png","id":"44","type":"friend","content":"1","timestamp":1660997157582},
//                {"username":"44","avatar":"https://video.imomo1.com/group1/M00/00/6C/ia8B-mLydyiEYKzCAAAAAD0M-Bc340.png","id":"44","type":"friend","content":"666666","timestamp":1660997164042}],
//                "friend30":[{"username":"客服1111","avatar":"https://video.imomo1.com/group1/M00/00/6C/ia8B-mLydyiEYKzCAAAAAD0M-Bc340.png","id":"30","type":"friend","content":"1","timestamp":1660993813424,"mine":true},{"username":"客服1111","avatar":"https://video.imomo1.com/group1/M00/00/6C/ia8B-mLydyiEYKzCAAAAAD0M-Bc340.png","id":"30","type":"friend","content":"2","timestamp":1660994822410,"mine":true}],
//                "friend31":[{"username":"客服1111","avatar":"https://video.imomo1.com/group1/M00/00/6C/ia8B-mLydyiEYKzCAAAAAD0M-Bc340.png","id":"31","type":"friend","content":"2","timestamp":1660993816381,"mine":true},{"username":"客服1111","avatar":"https://video.imomo1.com/group1/M00/00/6C/ia8B-mLydyiEYKzCAAAAAD0M-Bc340.png","id":"31","type":"friend","content":"33","timestamp":1660994828341,"mine":true}],
//                "friend32":[{"username":"客服1111","avatar":"https://video.imomo1.com/group1/M00/00/6C/ia8B-mLydyiEYKzCAAAAAD0M-Bc340.png","id":"32","type":"friend","content":"444","timestamp":1660994833107,"mine":true}]}}}
//
        SpUsers spUsers = spUsersService.getById(userid);

        HashMap userIdmap = new HashMap();
        HashMap msgs = new HashMap();
        HashMap history = new HashMap();
        HashMap chatlog = new HashMap();
        HashMap spread = new HashMap();
        spread.put("spread0","true");

        QueryWrapper<MsgsCollectArchived> wrapper = new QueryWrapper();
        wrapper.and(w ->w.eq("src_uid",userid));
        wrapper.or(w ->w.eq("dest_uid",userid));
//        wrapper.orderByDesc("msg_time");
        wrapper.select("src_uid");
        wrapper.groupBy("src_uid");
        wrapper.ge("msg_time",LocalDateTime.now().minusDays(3));
        List<Map<String, Object>> maps = msgsCollectArchivedService.listMaps(wrapper);
        for (Map obj :
                maps) {
            String toUserId = obj.get("src_uid").toString();
            SpUsers byId = spUsersService.getById(toUserId);
            HashMap hashMap1 = new HashMap();
            hashMap1.put("sign","");
            hashMap1.put("id",toUserId);
            hashMap1.put("avatar","https://video.imomo1.com/"+byId.getUserImg());
            hashMap1.put("username",byId.getUserNickname());
            hashMap1.put("status","online");
            hashMap1.put("name",toUserId);
            hashMap1.put("type","friend");
            hashMap1.put("historyTime",System.currentTimeMillis());

//            history.put("","");
            history.put("friend"+toUserId,hashMap1);
//            System.out.println("o = " + obj.toString());
            QueryWrapper<MsgsCollectArchived> wrapper1 = new QueryWrapper();
            wrapper1.and(w ->w.eq("src_uid",userid).eq("dest_uid",toUserId));
            wrapper1.or(w ->w.eq("src_uid",toUserId).eq("dest_uid",userid));
            wrapper1.orderByDesc("msg_time");
            List<MsgsCollectArchived> list = msgsCollectArchivedService.list(wrapper1);
            Collections.reverse(list);
            ArrayList arrayList = new ArrayList();
            for (MsgsCollectArchived msgsCollectArchived:
                 list) {
                JSONObject jsonObject = JSONObject.parseObject(msgsCollectArchived.getMsgContent());
                //{"msg":"444","msgType":"1","toName":"32","fromName":"客服1111","from":"29","to":"32","fromAvatar":"group1/M00/00/6C/ia8B-mLydyiEYKzCAAAAAD0M-Bc340.png"}
                HashMap hashMap = new HashMap();

                if (jsonObject.get("from").equals(toUserId)){
                    hashMap.put("username",byId.getUserNickname());
                    hashMap.put("avatar","https://video.imomo1.com/"+byId.getUserImg());
                }else {
                    hashMap.put("mine",true);
                    hashMap.put("username",spUsers.getUserNickname());
                    hashMap.put("avatar","https://video.imomo1.com/"+byId.getUserImg());
                }

                hashMap.put("id",msgsCollectArchived.getSrcUid() +"");
                hashMap.put("type","friend");
                hashMap.put("content",jsonObject.get("msg"));
                hashMap.put("timestamp",msgsCollectArchived.getMsgTime().getTime());
//                arrayList.add()
                arrayList.add(hashMap);
            }
            chatlog.put("friend"+toUserId,arrayList);


        }

        msgs.put("spread0",spread);
        msgs.put("chatlog",chatlog);
        msgs.put("history",history);
        userIdmap.put(userid+"",msgs);




//        Collections.reverse(list);


//        userIdmap.put(userid,);


//        return ResponseUtil.success(userIdmap);
        return ResponseEntity.ok(userIdmap);

    }
    /**
     * 用户列表
     * @Author lipeng
     * @Date 2022/5/23 22:00
     * @param userid
     * @return com.ruoyi.common.utils.status.ResponseUtil
     */
    @Log(title = "用户列表", businessType = BusinessType.OTHER)
    @RequestMapping("/userList")
    public ResponseEntity userList(Long userid ){

        HashMap hashMap = new HashMap();
        HashMap hashMap2 = new HashMap();
        QueryWrapper<MsgsCollectArchived> wrapper = new QueryWrapper();
        wrapper.and(w ->w.eq("src_uid",userid));
        wrapper.or(w ->w.eq("dest_uid",userid));
//        wrapper.orderByDesc("msg_time");
        wrapper.select("src_uid");
        wrapper.groupBy("src_uid");
        wrapper.ge("msg_time",LocalDateTime.now().minusDays(3));
        List<Map<String, Object>> userIdmaps = msgsCollectArchivedService.listMaps(wrapper);


//        QueryWrapper<SpUsers> wrapper = new QueryWrapper();
//        wrapper.select("user_id as id,user_nickname as username,user_login_state,user_img as avatar");
//        List<SpUsers> list = usersService.list();
        List list1 = new ArrayList<>();
        for (Map obj :
                userIdmaps) {
            String toUserId = obj.get("src_uid").toString();
            SpUsers spUsers = spUsersService.getById(toUserId);
            if (spUsers.getUserId() .equals(userid)){
                hashMap.put("username",spUsers.getUserNickname()+"");
                hashMap.put("id",spUsers.getUserId() +"");
                hashMap.put("status","online");
                hashMap.put("sign","");
                hashMap.put("avatar","https://video.imomo1.com/"+spUsers.getUserImg());
            }else {
                HashMap hashMap1 = new HashMap();
                hashMap1.put("username",spUsers.getUserId()+"");
                hashMap1.put("id",spUsers.getUserId()+"");
                hashMap1.put("status","online");
                hashMap1.put("sign","");
                hashMap1.put("avatar","https://video.imomo1.com/"+spUsers.getUserImg());
                list1.add(hashMap1);

            }

        }

//        for (SpUsers spUsers:list) {
//
//        }
        HashMap map = new HashMap();
        HashMap maps = new HashMap();
        map.put("list",list1);
        map.put("id",0);
        map.put("groupname","所有用户");

        ArrayList list2 = new ArrayList();
        list2.add(map);

        ArrayList list3 = new ArrayList();
        HashMap map1 = new HashMap();
        list3.add(map1);
        maps.put("friend",list2);
        maps.put("mine",hashMap);
        maps.put("group",list3);
        hashMap2.put("code",0);
        hashMap2.put("msg","");
        hashMap2.put("data",maps);
        return ResponseEntity.ok(hashMap2);

    }

    /**
     * 在线客服
     * &#064;Author  lipeng
     * @Date 2022/5/23 22:00
     * @return com.ruoyi.common.utils.status.ResponseUtil
     */
    @Log(title = "在线客服", businessType = BusinessType.OTHER)
    @PostMapping("/onlineService")
    public ResponseUtil onlineService(){

        QueryWrapper<SpUsers> wrapper = new QueryWrapper();
        wrapper.eq("user_state","2");
//        wrapper.eq("user_login_state","1");
        List<SpUsers> list = spUsersService.list(wrapper);

        return ResponseUtil.success(list);

    }


    /**
     * 在线客服
     * &#064;Author  lipeng
     * @Date 2022/5/23 22:00
     * @return com.ruoyi.common.utils.status.ResponseUtil
     */
    @PostMapping("/paymentChannel")
    public ResponseUtil paymentChannel(){

        QueryWrapper<PaymentChannel> wrapper = new QueryWrapper();
        wrapper.eq("is_del",0);
//        wrapper.eq("user_login_state","1");
        List<PaymentChannel> list = paymentChannelService.list(wrapper);

        return ResponseUtil.success(list);

    }


    /**
     * 在线客服
     * &#064;Author  lipeng
     * @Date 2022/5/23 22:00
     * @return com.ruoyi.common.utils.status.ResponseUtil
     */
    @PostMapping("/goldList")
    public ResponseUtil goldList(){

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("is_show",true);
        wrapper.eq("is_del",false);
        wrapper.orderByAsc("gold");


        return ResponseUtil.success(goldListService.list(wrapper));

    }



    /**
     * 收款方式
     * &#064;Author  lipeng
     * @Date 2022/5/23 22:00
     * @return com.ruoyi.common.utils.status.ResponseUtil
     */
    @PostMapping("/receipCodeList")
    public ResponseUtil receipCodeList(){

        HashMap map = new HashMap();

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("is_show",true);
        List list = receiptCodeService.list(wrapper);

        return ResponseUtil.success(list);

    }

    /**
     * 收款方式
     * &#064;Author  lipeng
     * @Date 2022/5/23 22:00
     * @return com.ruoyi.common.utils.status.ResponseUtil
     */
    @PostMapping("/receipCodeListV2")
    public ResponseUtil receipCodeListV2(String status){

        HashMap map = new HashMap();

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.select("status");
        wrapper.eq("is_show",true);
        wrapper.groupBy("status");
        List list = receiptCodeService.listMaps(wrapper);

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("is_show",true);
        queryWrapper.eq("status",status);

        map.put("status",list);
        map.put("list",receiptCodeService.list(queryWrapper));
        return ResponseUtil.success(map);

    }


    /**
     * 收款
     * @Author lipeng
     * @Date 2022/8/22 20:53
     * @param userId  用户id
     * @param type 1： 开通会员   2 充值金币
     * @param id
     * @return com.ruoyi.common.utils.status.ResponseUtil
     */
    @Log(title = "支付请求")
    @PostMapping("/ZhifuFM")
    public ResponseUtil zhifuFM(Long userId,Integer type ,Integer id){

        SpUsers spUsers = spUsersService.getById(userId);

        Map<String, String> paramMap = new HashMap<>();// post请求的参数
        BigDecimal bigDecimal;
        String amount = "1.00";// 支付金额

        SpConsumeRecord consumeRecord = new SpConsumeRecord();
        HashMap map = new HashMap();
        switch (type){
            case 1:
                VipCategory vipCategory = vipCategoryService.getById(id);
                Integer time = vipCategory.getTime();
                Integer userVipType = vipCategory.getType();
                map.put("time",time);
                map.put("userVipType",userVipType);
                bigDecimal = vipCategory.getFavorable().setScale(2, BigDecimal.ROUND_DOWN);


                paramMap.put("subject", "开通会员");
                paramMap.put("body", "开通会员");
                consumeRecord.setDescs("开通会员");
                break;
            case 2:
                GoldList goldList = goldListService.getById(id);
                Long gold = goldList.getGold();
                map.put("gold",gold);
                bigDecimal = goldList.getMoney().setScale(2, BigDecimal.ROUND_DOWN);


                paramMap.put("subject", "充值金币");
                paramMap.put("body", "充值金币");

                break;

            default:
                return ResponseUtil.fail(-1,"参数异常");
        }


        amount = bigDecimal.toString();

        consumeRecord.setMoney(bigDecimal);
        consumeRecord.setTradeNo(com.quyang.voice.utils.StringUtils.generateOrderNumber());
        consumeRecord.setPayType(2);
        consumeRecord.setUserId(userId);
        consumeRecord.setCurrentBalance(spUsers.getUserGlod());
        consumeRecord.setChangeType(2);
        consumeRecord.setType(11);
        consumeRecord.setOperationAmount(bigDecimal);
        consumeRecord.setCreateTime(new Date());

//        consumeRecordService.save(consumeRecord);

        String merchantNum = "155581686992994304";// 商户号
        String orderNo = StringUtils.generateOrderNumber();// 商户订单号

        map.put("userId",userId);
        map.put("type",type);
        map.put("id",id);
        map.put("amount",amount);

        redisCache.setCacheMap(orderNo,map);

        redisCache.setCacheObject("order:"+orderNo,consumeRecord);
        String notifyUrl = "https://api.imomo1.com/xqsp/callback/zhifuFM/"+orderNo;// 填写您的接收支付成功的异步通知地址
        String returnUrl = "";// 同步通知地址
        String payType = "alipay";// 请求支付类型
        String attch = ""; // 附加参数
        String secretKey = "7ce39b9416ac8046073bc731ac3262a2";//商户密钥
        String sign = merchantNum + orderNo + amount + notifyUrl + secretKey;
        sign = DigestUtils.md5DigestAsHex(sign.getBytes());
//        sign = MD5Utils.md5(sign);// md5签名
        System.out.println(sign);
        String url = "http://api-16jx3se3vt34.zhifu.fm.it88168.com/api/startOrder"; //"http://zfapi.nnt.ltd/api/startOrder";// 发起订单地址

        paramMap.put("merchantNum", merchantNum);
        paramMap.put("orderNo", orderNo);
        paramMap.put("amount", amount);
        paramMap.put("notifyUrl", notifyUrl);
        paramMap.put("returnUrl", returnUrl);
        paramMap.put("payType", payType);
        paramMap.put("attch", attch);
        paramMap.put("sign", sign);

        System.out.println(JSONObject.toJSON(paramMap));
//		String result = HttpUtil.post(url, paramMap); //JDK11
//		System.out.println(result);
        String result = null;
        JSONObject ret = new JSONObject();

        HashMap hashMap = new HashMap();

        String payUrl = redisCache.getCacheObject("payUrl:"+userId);

//        if (payUrl != null){
//         return    ResponseUtil.success(payUrl);
//        }


        try {
            String paramStr = toParams(paramMap);
            System.out.println(paramStr);
            CloseableHttpClient httpclient = HttpClientBuilder.create().build();
            HttpPost httpost = new HttpPost(url + "?" + paramStr); // 设置响应头信息
            String userAgent = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.87 Safari/537.36";
            httpost.setHeader("User-Agent",userAgent); //防止被防火墙拦截 Apache httpclient

            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(5000).setConnectionRequestTimeout(1000)
                    .setSocketTimeout(5000).build();
            httpost.setConfig(requestConfig);

            HttpResponse retResp = httpclient.execute(httpost);
            result = EntityUtils.toString(retResp.getEntity(), "UTF-8");
            System.out.println(result);
        }
        catch (ClientProtocolException e1) {
            e1.printStackTrace();
        }
        catch (IOException e1) {
            e1.printStackTrace();
        }catch (ParseException e1) {
            e1.printStackTrace();
        }
        if(result.startsWith("{")) { //为了您的业务健壮性，建议简单判断或者增加下容错逻辑
            ret = JSONObject.parseObject(result);
            JSONObject data = ret.getJSONObject("data");
            if (data == null){
                return ResponseUtil.fail(-1,"请求频繁,请五分钟之后再试");
            }else {
                String string = ret.getJSONObject("data").getString("payUrl");
                redisCache.setCacheObject("payUrl:"+userId,string,300, TimeUnit.SECONDS);
                return ResponseUtil.success(string);
            }

        }else {
            ret.put("code", "error");
            ret.put("msg", "发起支付订单失败，接口返回信息异常");
            return ResponseUtil.fail(-1,"支付异常");
        }

    }

//    public static void main(String[] args) {
//        BigDecimal bigDecimal = new BigDecimal(String.valueOf(1));
//        BigDecimal bigDecimal1 = bigDecimal.setScale(0, BigDecimal.ROUND_DOWN);
//        System.out.println("bigDecimal1 = " + bigDecimal1);
//        BigDecimal bigDecimal2 = bigDecimal1.setScale(2, BigDecimal.ROUND_DOWN);
//        System.out.println("bigDecimal2 = " + bigDecimal2.toString());
//    }
//

    @PostMapping("/payment")
    public   ResponseUtil payment(Integer type,  Long userId,Integer payType ,Integer id){

        BigDecimal bigDecimal;
        String amount = "1.00";// 支付金额
        SortedMap map = new TreeMap();
        SpConsumeRecord consumeRecord = new SpConsumeRecord();

        switch (type){
            case 1:
                VipCategory vipCategory = vipCategoryService.getById(id);
                bigDecimal = vipCategory.getFavorable().setScale(2, BigDecimal.ROUND_DOWN);


                map.put("name","开通会员");
                break;
            case 2:
                GoldList goldList = goldListService.getById(id);
                bigDecimal = goldList.getMoney().setScale(2, BigDecimal.ROUND_DOWN);
                map.put("name","充值金币");
                break;

            default:
                return ResponseUtil.fail(-1,"参数异常");
        }


        amount = bigDecimal.toString();




        map.put("pid","1010");

        switch (payType){
            case 1:
                map.put("type","alipay");
                break;
            case 2:
                map.put("type","wxpay");
                break;
        }
        String order = StringUtils.generateOrderNumber();

        map.put("out_trade_no",order);
        map.put("notify_url","https://api.imomo1.com/xqsp/callback/zhifuFM");
        map.put("return_url","http://47.100.31.158:82/index.html");
        map.put("money",bigDecimal.toString());
        map.put("clientip","127.0.0.1");
        map.put("device","mobile");
        map.put("param",id.toString());

        String s = sortParams(map);
        System.out.println("s = " + s);
        System.out.println("s = " + s+"&key="+"lX6V9uXR6Xc5u68V6uL4pR5O6x8U6URv");
        String s1 = s + key;
        String s2 = DigestUtils.md5DigestAsHex(s1.getBytes());
        System.out.println("s2 = " + s2);
        map.put("sign",s2);
        map.put("sign_type","MD5");

        String s3 = null;
        try {
            String s4 = sortParams(map);
            System.out.println("s4 = " + s4+"&key=" + "lX6V9uXR6Xc5u68V6uL4pR5O6x8U6URv");
            System.out.println("s4 = " + s4);
            s3 = HttpClient.doPost("https://epay.05669.xyz/mapi.php", map,10000,10000);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("s3 = " + s3);
        return ResponseUtil.success(JSONObject.parseObject(s3));
    }



    /**
     * 根据参数名称对参数进行字典排序
     * @param params
     * @return
     */
    private static String sortParams(SortedMap<String, String> params) {
        StringBuffer sb = new StringBuffer();
        Set<Map.Entry<String, String>> es = params.entrySet();
        Iterator<Map.Entry<String, String>> it = es.iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> entry = it.next();
            String k = entry.getKey();
            String v = entry.getValue();
            sb.append(k + "=" + v + "&");
        }
        return sb.substring(0, sb.lastIndexOf("&"));
    }


    /**
     　　* 把数组所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
     　　* @param params 需要排序并参与字符拼接的参数组
     　　* @return 拼接后字符串
     　　* @throws UnsupportedEncodingException
     　　*/
    public String toParams(Map<String, String> params) throws UnsupportedEncodingException {
        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);
        String prestr = "";
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);
            value = URLEncoder.encode(value, "UTF-8");
            if (i == keys.size() - 1) {// 拼接时，不包括最后一个&字符
                prestr = prestr + key + "=" + value;
            }
            else {
                prestr = prestr + key + "=" + value + "&";
            }
        }
        return prestr;
    }







}
